package com.dqp.cslggroup.School;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import androidx.appcompat.widget.Toolbar;
import com.alibaba.fastjson.JSONObject;
import com.dqp.cslggroup.Api.jwxtApi;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.AlertDialog;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.Result;
import com.dqp.cslggroup.Util.StringUtil;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.bean.course;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 董琴平
 * @version 1.0
 * @date 2021/9/6 1:09
 */
public class shareCourse extends BaseActivity {
    Button generate, submit;
    ExecutorService threadPool = Executors.newFixedThreadPool(2);
    private ViewStub viewstub_loading, viewstub_loading1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share_course);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        EventBus.getDefault().register(this);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        initCmp();
    }

    public void initCmp() {
        generate = findViewById(R.id.generate_token);
        submit = findViewById(R.id.submit_token);
        viewstub_loading = findViewById(R.id.viewstub_loading);
        viewstub_loading1 = findViewById(R.id.viewstub_loading1);
        generate.setOnClickListener(v -> {
            viewstub_loading.setVisibility(View.VISIBLE);
            generateToken();
        });
        submit.setOnClickListener(v1 -> {
            String token = onClickPaste();
            if (StringUtil.isEmpty(token)) {
                ToastUtil.showToast("未复制分享口令");
                return;
            }
            if (StringUtil.isContainChinese(token)) {
                ToastUtil.showToast("复制内容不是分享口令");
            }
            submitToken(token);
        });
    }

    public void generateToken() {
        threadPool.execute(() -> {
            List<course> courses = MyApplication.getDaoInstant().getCourseDao().loadAll();
            if (courses != null && courses.size() > 0) {
                course course = courses.get(0);
                String year = course.getXnm();
                String sno = course.getSno();
                String term = course.getXqm();
                if (!StringUtil.isEmpty(sno, year, term)) {
                    JSONObject jsonObject = jwxtApi.shareCourse(sno, year, term);
                    if (Result.jsonResultIsTure(jsonObject))
                        EventBus.getDefault().post(new MessageEvent("shareCourse", 0, jsonObject.getString("token")));
                } else ToastUtil.showToast("课表相关数据不匹配");
            }

        });
    }

    public void submitToken(String token) {
        AlertDialog alertDialog = new AlertDialog(this);
        alertDialog.builder();
        alertDialog.setGone()
                .setTitle("课表口令")
                .setMsg(token)
                .setMsgGravity(false)
                .setNegativeButton("获取", R.color.colorAccent, v1 -> {
                    alertDialog.dismiss();
                    viewstub_loading1.setVisibility(View.VISIBLE);
                    threadPool.execute(() -> {
                        JSONObject jsonObject = jwxtApi.getShareCourse(token);
                        if (Result.jsonResultIsTure(jsonObject)) {
                            EventBus.getDefault().post(new MessageEvent("shareCourse", 3, "获取完成"));
                        } else
                            EventBus.getDefault().post(new MessageEvent("shareCourse", 3, jsonObject.getString("resultMsg")));
                    });

                })
                .setPositiveButton("取消", R.color.colorAccent, v2 -> {
                    alertDialog.dismiss();
                })
                .show();
    }

    public void onClickCopy(String token) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", token);
        // 将ClipData内容放到系统剪贴板里。
        assert cm != null;
        cm.setPrimaryClip(mClipData);
        ToastUtil.showToast("✌复制成功");
    }

    public String onClickPaste() {
        ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
        assert clipboard != null;
        ClipData clipData = clipboard.getPrimaryClip();
        if (clipData != null && clipData.getItemCount() > 0) {
            CharSequence text = clipData.getItemAt(0).getText();
            String pasteString = text.toString();
            return pasteString;
        }
        return null;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("shareCourse")) {
            switch (event.getWhat()) {
                case 0:
                    if (event.getMessage() == null) {
                        ToastUtil.showToast("没有复制内容");
                        break;
                    }
                    viewstub_loading.setVisibility(View.GONE);
                    AlertDialog alertDialog = new AlertDialog(this);
                    alertDialog.builder();
                    alertDialog.setGone()
                            .setTitle("分享口令")
                            .setMsg(event.getMessage())
                            .setMsgGravity(false)
                            .setNegativeButton("复制", R.color.colorAccent, v1 -> {
                                alertDialog.dismiss();
                                onClickCopy(event.getMessage());

                            })
                            .setPositiveButton("取消", R.color.colorAccent, v2 -> {
                                alertDialog.dismiss();
                            })
                            .show();
                    break;
                case 1:
                    viewstub_loading.setVisibility(View.GONE);
                    break;
                case 2:
                    viewstub_loading1.setVisibility(View.GONE);
                    break;
                case 3:
                    viewstub_loading1.setVisibility(View.GONE);
                    ToastUtil.showToast(event.getMessage());
                    break;

            }
        }
    }


}
